#include <getopt.h>
#include <vector>
#include <algorithm>
#include <stdio.h>

#include "fmerge.h"
#include "idngram_merge.h"

static option long_options[] = {
  {"NMax", 1, 0, 'n'},
  {"out", 1, 0, 'o'},
  {0, 0, 0, 0}
};

static int N = 0;
static int paraMax = 0;
static char *output = NULL;
static char *swapfile = NULL;

void ShowUsage()
{
  printf("........\n");
  printf("........\n");
}

static void getParameters(int argc, char* const argv[])
{
  int optiona_index = 0;
  int c;
  while ((c = getopt_long(argc, argv, "n:o:", long_options, &optiona_index))) {
    switch (c) {
    case 'n':
      N = atoi(strdup(optarg));
      break;
    case 'o':
      output = strdup(optarg);
      break;
    default:
      ShowUsage();
      exit(1000);
    }
  }
  if (N < 1 || N > 3 || output == NULL) {
    ShowUsage();
    exit(1000);
  }
}

#ifdef TMERGE

int main(int argc, char* argv[])
{
  getParameters(argc, argv);
  FILE *out = fopen(output, "wb+");
  std::vector<FILE *> idngram_files;

  if (optind >= argc)
    ShowUsage();
  while (optind < argc) {
    printf("Open %s...", argv[optind]);
    FILE *fp = fopen(argv[optind++], "rb");
    if (fp == NULL) {
      printf("error\n");
      exit(200);
    }
    idngram_files.push_back(fp);
    printf("\n");
  }
  printf("Mergering...");
  switch (N) {
  case 1:
    ProcessingIdngramMerge<1>(out, idngram_files);
    break;
  case 2:
    ProcessingIdngramMerge<2>(out, idngram_files);
    break;
  case 3:
    ProcessingIdngramMerge<3>(out, idngram_files);
    break;
  }
  printf("\n");
  fclose(out);
  for (int i = 0; i < idngram_files.size(); ++i)
    fclose(idngram_files[i]);
  return 0;
}
#endif
